package org.tea.domain.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.tea.application.common.CookieProp;
import org.tea.application.configuration.CrawlServerConfiguration;
import org.tea.application.service.CookieService;
import org.tea.common.ResponseResult;
import org.tea.domain.entity.CookiePropEntity;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * @author lxh
 */
@Service("jdCookieService")
public class JdCookieServiceImpl
        implements CookieService {

    @Resource
    private CrawlServerConfiguration crawlServerConfiguration;

    @Resource
    private ObjectMapper mapper;

    public JdCookieServiceImpl() {
    }

    @Override
    public List<CookieProp> createCookies(String url) {
        String cookieServerUrl = "http://" + crawlServerConfiguration.getHost()
                + ":" + crawlServerConfiguration.getPort()
                + "/" + crawlServerConfiguration.getCookieServerPath()
                + "/cookie/validJdCookie";
        String res = new RestTemplate().postForObject(cookieServerUrl, null, String.class);
        try {
            ResponseResult<List<CookiePropEntity>> result =
                    mapper.readValue(res, new TypeReference<ResponseResult<List<CookiePropEntity>>>() {
                    });
            if (result.getCode() != 200) {
                throw new RuntimeException("当前无可用的 Cookie");
            }
            return Lists.newArrayList(result.getData());
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int releaseCookie(String cookieId) {
        String cookieServerUrl = "http://" + crawlServerConfiguration.getHost()
                + ":" + crawlServerConfiguration.getPort()
                + "/" + crawlServerConfiguration.getCookieServerPath()
                + "/cookie/releaseJdCookie/" + cookieId;
        ResponseResult<?> response =
                new RestTemplate().postForObject(cookieServerUrl, null, ResponseResult.class);
        return !Objects.isNull(response) && response.getCode() == 200 ? 1 : 0;
    }
}
